﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Reflection;

namespace GtsServer.Common
{
    public class ObjectToJson<T>
    {
        //List转成json
        public static string ListToJson<T>(string jsonName, IList<T> IL)
        {

            System.Text.StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + jsonName + "\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {

                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        /// <summary>
        /// 将List序列化Json
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string JsonSerializer(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        /// 将json转成list
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JsonToList(string json)
        {
            //将json格式的字符串转为OrderList对象
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream mems = new MemoryStream(Encoding.UTF8.GetBytes(json));
            T t = (T)ser.ReadObject(mems);

            return t;
        }
    }
}
